﻿using System.Windows.Media.Imaging;
using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace HistogramLr.Models
{
	public class DrawUtils
	{
		/// <summary>
		/// Colorレベルメータの作成
		/// </summary>
		/// <param name="colorLevel"></param>
		/// <param name="cvColor"></param>
		/// <returns></returns>
		public static WriteableBitmap DrawColorLevel(int colorLevel, CvScalar cvColor)
		{
			using (IplImage image = new IplImage(256, 8, BitDepth.U8, 3))
			{
				// ポインタの色（少し明るめに設定）
				// TODO:もしくはコール元で色を決定。
				cvColor.Val0 += 0x40; if (cvColor.Val0 > 0xFF) cvColor.Val0 = 0xff;
				cvColor.Val1 += 0x40; if (cvColor.Val1 > 0xFF) cvColor.Val1 = 0xff;
				cvColor.Val2 += 0x40; if (cvColor.Val2 > 0xFF) cvColor.Val2 = 0xff;

				image.Zero();
				image.DrawLine(colorLevel - 2, 3, colorLevel - 2, 7, cvColor);
				image.DrawLine(colorLevel - 1, 2, colorLevel - 1, 7, cvColor);
				image.DrawLine(colorLevel, 1, colorLevel, 7, cvColor);
				image.DrawLine(colorLevel + 1, 2, colorLevel + 1, 7, cvColor);
				image.DrawLine(colorLevel + 2, 3, colorLevel + 2, 7, cvColor);
				return WriteableBitmapConverter.ToWriteableBitmap(image);
			}
		}

		/// <summary>
		/// Colorレベルメータの作成（RGB混合）
		/// </summary>
		/// <param name="lR"></param>
		/// <param name="lG"></param>
		/// <param name="lB"></param>
		/// <param name="cR"></param>
		/// <param name="cG"></param>
		/// <param name="cB"></param>
		/// <returns></returns>
		public static WriteableBitmap DrawColorLevel(int lR, int lG, int lB, CvScalar cR, CvScalar cG, CvScalar cB)
		{
			using (IplImage imageR = WriteableBitmapConverter.ToIplImage(DrawColorLevel(lR, cR)))
			using (IplImage imageG = WriteableBitmapConverter.ToIplImage(DrawColorLevel(lG, cG)))
			using (IplImage imageB = WriteableBitmapConverter.ToIplImage(DrawColorLevel(lB, cB)))
			{
				imageR.Add(imageG, imageR);
				imageR.Add(imageB, imageR);

				return WriteableBitmapConverter.ToWriteableBitmap(imageR);
			}
		}
	}
}
